/*
 * Package il.ac.biu.cs.grossmm.test.SimpleProtocol
 * File Message.java
 * 
 * This is a part of presence service framework API. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.foo.protocol;

import java.util.StringTokenizer;

public abstract class Message {
	protected String tid;
	public static char MSG_DELIMETER='\0';
	
	public static char PARAM_DELIMETER='\1';
	
	
	protected static String PAR_DELIM_STR =Character.toString(PARAM_DELIMETER);
	protected static byte[] MSG_DELIM_BIN =Character.toString(MSG_DELIMETER).getBytes();
	
	
	static {
		try {
			MSG_DELIM_BIN =Character.toString(MSG_DELIMETER).getBytes("utf-8");
		} catch( Exception e) {}
	}
	
	protected Message() {
		
	}
	
	protected Message(String  tid2)
	{
		tid = tid2;
	}

	public String getTransactionId() {
		return tid;
	}
	
	
	static Message parse(String str) {
		StringTokenizer st = new StringTokenizer(str, PAR_DELIM_STR);
		
		int count = st.countTokens();
		
		String tid, cmd;
		
		if( count < 2 ) {
			if( count == 0 )
				return null;
			
			tid = st.nextToken();
			
			return new UnknownRequest(tid, null);
		}
		
		tid = st.nextToken();
		cmd = st.nextToken();
		
		if( Character.isDigit(cmd.charAt(0)) ) {
			// response
			int code = Integer.parseInt(cmd);
			
			
			String msg = "";
			
			if( st.hasMoreTokens() )
				msg = st.nextToken();
			
			return new Response(tid, code, msg); 
		}
		
		RequestFactory factory = Request.factories.get(cmd);
		
		if( factory == null )
			return new UnknownRequest(tid, cmd);
		
		String[] params = new String[count-2];
		
		for (int i = 0; i < params.length; i++) {
			params[i] = st.nextToken();
		} 
		
		return factory.getRequest(tid, params);
	}
}
